// import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import { Alert, Button, Space, Switch, Tag, message, Popconfirm } from "antd";
import { memo, useState, useEffect, useRef } from "react";
import AddNewModal from "./AddNewModal";
import CommonLoading from "@/components/CommonLoading";
import { labelStrategyList, updateStatusLabelStrategyOp, deleteLabelStrategyOp } from "../../service";
import CommonTable from "@/components/CommonTable";
import { labelColorMap } from "@/utils/config";

const renderAlertMsg = () => {
	return (
		<div>
			<div>1、符合规则的订单，支持自动打上标签、或标记异常、或设置发货仓；</div>
			<div>2、如果订单满足多个规则，则标签会多个规则都执行，异常和设置发货仓只按最高优先级处理</div>
		</div>
	);
};

const TabIntelligentTag = ({ type }) => {
	const [tableData, setTableData] = useState([]); //表格数据
	const [visible, setVisible] = useState(false); //新增/编辑弹窗
	const [visibleType, setVisibleType] = useState("add"); //弹窗的状态
	const [recordData, setRecordData] = useState({}); //单行的数据
	const [loading, setLoading] = useState(false);

	const divEl = useRef(null);

	useEffect(() => {
		if (type == 1) {
			getLabelStrategyList();
		}
	}, [type]);

	//表格滚动高度
	const [scrollHeight, setScrollHeight] = useState(580);

	//监听窗口尺寸变化计算一下高度
	useEffect(() => {
		window.addEventListener("resize", () => {
			handleSetHeight();
		});
		return () => {
			window.removeEventListener("resize", () => {
				handleSetHeight();
			});
		};
	}, []);

	useEffect(() => {
		handleSetHeight();
	}, []);

	//计算表格的滚动高度
	const handleSetHeight = () => {
		try {
			const sumHeight = document.getElementById("sectionContent").clientHeight;
			const searchHeight = divEl && divEl.current ? divEl.current.clientHeight : 0;
			const finalHeight = sumHeight - (searchHeight + 160);
			setScrollHeight(finalHeight);
		} catch (e) {
			console.log(e);
		}
	};

	//查询表格数据
	const getLabelStrategyList = async () => {
		setLoading(true);
		// setTableData([]);
		const { success, data = [] } = await labelStrategyList({
			current: 1,
			size: 500
		});
		if (success) {
			setTableData(data);
		}
		setLoading(false);
	};

	//切换开关
	const handleSwitch = async (e, record) => {
		setLoading(true);
		const { success, msg } = await updateStatusLabelStrategyOp({ status: e ? 1 : 0, id: record.id });
		if (success) {
			message.success(msg);
			getLabelStrategyList();
		}
		setLoading(false);
	};

	//删除当前数据
	const handleDeleteItems = async record => {
		setLoading(true);
		const { msg = "", success } = await deleteLabelStrategyOp({ id: record.id });
		if (success) {
			message.success(msg);
			getLabelStrategyList();
		}
		setLoading(false);
	};

	//单行点击编辑
	const handleEditItem = (record, type) => {
		setVisible(true);
		setRecordData(record);
		setVisibleType(type);
	};

	const tableColumns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "标签规则名称",
			dataIndex: "name",
			key: "name",
			width: 120
		},
		{
			title: "规则编号",
			dataIndex: "number",
			key: "number",
			width: 100
		},
		{
			title: "优先级",
			dataIndex: "level",
			key: "level",
			width: 100
		},
		{
			title: "标签",
			dataIndex: "labelConfigList",
			key: "labelConfigList",
			width: 100,
			render(text) {
				return (
					<>
						{text.length
							? text.map(item => (
									<Tag key={item.id} color="gold">
										{labelColorMap[item.name] ? labelColorMap[item.name] : item.name}
									</Tag>
								))
							: "/"}
					</>
				);
			}
		},
		{
			title: "标记异常",
			dataIndex: "errorConfig",
			key: "errorConfig",
			width: 100,
			render(text) {
				return <>{text?.name ? text?.name : "/"}</>;
			}
		},
		{
			title: "设置发货仓",
			dataIndex: "deliveryWarehouseName",
			key: "deliveryWarehouseName",
			width: 100
		},
		{
			title: "最新设置时间",
			dataIndex: "updateTime",
			key: "updateTime",
			width: 120
		},
		{
			title: "是否开启",
			dataIndex: "status",
			key: "status",
			width: 100,
			render(text, record) {
				return (
					<Switch
						checkedChildren="开启"
						unCheckedChildren="关闭"
						checked={record.status == 1}
						onClick={e => handleSwitch(e, record)}
					/>
				);
			}
		},
		{
			title: "操作",
			width: 120,
			render: record => {
				return (
					<>
						<Button onClick={() => handleEditItem(record, "edit")} type="link" size="small">
							编辑
						</Button>
						<Popconfirm title="确定删除?" onConfirm={() => handleDeleteItems(record)} okText="确定" cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</>
				);
			}
		}
	];

	//新增标签规则
	const AddNewModalProps = {
		visible,
		type: visibleType,
		recordData,
		handleCancel() {
			setVisible(false);
			setVisibleType("add");
			setRecordData({});
		},
		handleOk() {
			getLabelStrategyList();
			setVisible(false);
			setVisibleType("add");
			setRecordData({});
		}
	};

	//表格
	const tableProps = {
		data: tableData,
		columns: tableColumns,
		handleRowKey(record) {
			return record.id;
		},
		scroll: { y: scrollHeight }
	};

	return (
		<div direction="vertical" size={20}>
			<div ref={divEl}>
				<Alert message={renderAlertMsg()} type="info" showIcon />
				<Button style={{ marginTop: "16px", marginBottom: "16px" }} onClick={() => setVisible(true)}>
					新增智能标签规则
				</Button>
			</div>
			{/* <CommonTable
				columns={tableColumns}
				dataSource={tableData}
				pagination={false}
				scroll={{ y: "calc(100vh - 350px)" }}
				rowKey={"id"}
			/> */}
			<CommonTable {...tableProps} />

			{visible && <AddNewModal {...AddNewModalProps} />}
			<CommonLoading loading={loading} />
		</div>
	);
};
export default memo(TabIntelligentTag);
